package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Autowired
    private OrdersettingService ordersettingService;

    //根据日期修改可预约人数
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting) {

        ordersettingService.editNumberByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);

    }

    //根据年月查询对应的预约设置信息
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@RequestParam String month) {

        log.info("根据年月查询预约信息{}", month);

        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, ordersettingService.getOrderSettingByMonth(month));
    }
    //上传excel文件

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {

        log.info("上传文件{}", excelFile);

        try {
            List<String[]> excel = POIUtils.readExcel(excelFile);
            System.out.println(excel);

            //存到数据库
            ordersettingService.add(excel);

        } catch (IOException e) {
            log.info("上传文件失败");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    //表格下载
    @GetMapping("/download")
    public String download(@RequestParam String filename, HttpServletResponse response) throws IOException {

        log.info("表格下载{}", filename);

        ordersettingService.download(filename, response);

        return "文件下载";
    }

}
